//
//  HealthManagerViewController.m
//  QinrenManagers
//
//  Created by easaa on 15/7/23.
//  Copyright (c) 2015年 easaa. All rights reserved.
//

#import "HealthManagerViewController.h"

#import "HealthGroupViewController.h"

#import "ChatController.h"
#import "ApplyViewController.h"

#import "GroupModel.h"
#import "FriendModel.h"

#import "FriendListCell.h"

#import "UIImageView+EMWebCache.h"

@interface HealthManagerViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchDisplayDelegate>

{
    HealthGroupViewController * _groupController;
}

@property (nonatomic, strong) UITableView    * friendTableView;

@property (nonatomic, strong) NSMutableArray * dataSource;
/**装载好友用来搜索*/
@property (nonatomic, strong) NSMutableArray * friendNameArray;

/**搜索结果数组*/
@property (nonatomic, strong) NSMutableArray * resultArray;

@property (nonatomic, strong) UISearchBar    * searchBar;

@property (nonatomic, strong) UISearchDisplayController * searchController;

@end

@implementation HealthManagerViewController



- (instancetype)init
{
    self = [super init];
    if (self) {
        _dataSource = [NSMutableArray array];
        _resultArray = [NSMutableArray array];
        _friendNameArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self requestForGroupData];
    [self creatUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
    [_dataSource removeAllObjects];
    
    [self requestForGroupData];

}

- (void)requestForGroupData {
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [SVProgressHUD show];
    User *user = [User sharedUser];
    
    NSDictionary *parameters = @{@"username":user.hx_username};
    NSLog(@"%@",parameters);
    [manager GetWithParameters:parameters method:@"get.hxuser.friend" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;
        
        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"管家好友的dictonary :%@",[dictionary description]);
        
        [_friendNameArray removeAllObjects];
        [_dataSource removeAllObjects];
        if ([[dictionary objectForKey:@"verification"]intValue] == 1)
        {
            
            
            for (NSDictionary *dataDic in dictionary[@"data"]) {
                
                FriendModel * friendModel = [[FriendModel alloc]init];
                [friendModel setValuesForKeysWithDictionary:dataDic];
                
                [_dataSource addObject:friendModel];
                
                [_friendNameArray addObject:friendModel.name];
                
            }
            [_friendTableView reloadData];
            [SVProgressHUD dismiss];
            
        }
        else
        {
            NSString *error = [dictionary objectForKey:@"error"];
            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD showErrorWithStatus:error];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
    }];
    
}

- (void)creatUI
{
    //搜索框
    //_searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 64, SCREEN_W, 44)];
    _searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 44)];
    
    _searchBar.placeholder = @"搜索";
    
    //_searchBar.backgroundColor = [UIColor greenColor];
    
    //搜索结果展示
    // 用 searchbar 初始化 SearchDisplayController
    // 并把 searchDisplayController 和当前 controller 关联起来
    _searchController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
    
    _searchController.delegate = self;
    // searchResultsDataSource 就是 UITableViewDataSource
    _searchController.searchResultsDataSource = self;
    // searchResultsDelegate 就是 UITableViewDelegate
    _searchController.searchResultsDelegate = self;
    
    //主界面数据展示
    // _customerTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_searchBar.frame), SCREEN_W, SCREEN_H-64-44) style:UITableViewStyleGrouped];
    _friendTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H) style:UITableViewStylePlain];
    
    
    _friendTableView.backgroundColor = [UIColor whiteColor];
    _friendTableView.dataSource=self;
    _friendTableView.delegate=self;
    
    UINib * nib = [UINib nibWithNibName:@"FriendListCell" bundle:nil];
    
    [_friendTableView registerNib:nib forCellReuseIdentifier:@"ListCell"];
    
    _friendTableView.tableHeaderView = _searchBar;
    _friendTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    
    [self.view addSubview:_friendTableView];
    
    
}

#pragma mark - ---------------------------Search Delegate----------------------------

//只要用户在searchbar中输入内容就会触发该方法
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    //每次搜索之前，清空searchResults
    [_resultArray removeAllObjects];
    NSLog(@"%@", searchString);
    
    //    for (NSArray *section in _dataSourceArry)
    //    {
    //        //通过谓词过滤数据
    //        NSPredicate *p = [NSPredicate predicateWithFormat:@"self contains[c] %@", searchString];
    //
    //        NSArray *a = [section filteredArrayUsingPredicate:p];
    //
    //        //实现排序
    //        //self == 排序条件
    //        //NO    == 升序(YES)or降序(NO)
    //        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO];
    //        NSArray *s = [a sortedArrayUsingDescriptors:@[sort]];
    //        NSLog(@"%@", s);
    //        [_resultArray addObjectsFromArray:s];
    //    }
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",searchString];//用于过滤
    _resultArray = [NSMutableArray arrayWithArray:[_friendNameArray filteredArrayUsingPredicate:predicate]];
    
    return YES;
}





#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(tableView != _friendTableView)
    {
        return 1;
    }
    else
        return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    
    if(tableView != _friendTableView)
    {
        return [_resultArray count];
    }
    else {
        if (section == 0) {
            //return 3;
            return 2;
            //        return 1;
        }
        return [_dataSource count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    
    if(tableView != _friendTableView){
        
        static NSString * cellName=@"cell";
        
        cell = [tableView dequeueReusableCellWithIdentifier:cellName];
        if(cell==nil)
        {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellName];
        }
        
        cell.textLabel.text = [_resultArray objectAtIndex:indexPath.row];
    }
    else {
        FriendListCell *cell;
        
        cell = (FriendListCell *)[tableView dequeueReusableCellWithIdentifier:@"ListCell"];
        if (cell == nil) {
            cell = [[FriendListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FriendListCell"];
        }


        if (indexPath.section == 0 && indexPath.row == 0) {
            cell.iconImageView.image = [UIImage imageNamed:@"newFriends"];
            cell.friendNameLabel.text = NSLocalizedString(@"title.apply", @"Application and notification");
        }
        else if (indexPath.section == 0 && indexPath.row == 1) {
            cell.iconImageView.image = [UIImage imageNamed:@"groupPrivateHeader"];
            cell.friendNameLabel.text = NSLocalizedString(@"title.group", @"Group");
        }
        else {
            if(_dataSource.count>0){
                
                FriendModel *friendModel = _dataSource[indexPath.row];
                // cell.iconImageView.image = [UIImage imageNamed:@"chatListCellHead.png"];
                
                [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:friendModel.img] placeholderImage:[UIImage imageNamed:@"chatListCellHead.png"]];
                //cell.friendNameLabel.text = _friendNameArray[indexPath.row];
                cell.friendNameLabel.text = friendModel.name;
            
            
            }
           
        }
        
            return cell;
    }

    return cell;
}




#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 0;
    }
    else{
        return 22;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    if (section == 0 )
    {
        return nil;
    }
    
    UIView *contentView = [[UIView alloc] init];
    [contentView setBackgroundColor:Lightlightcolor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 100, 22)];
    label.backgroundColor = [UIColor clearColor];
    [label setText:@"联系人"];
    [contentView addSubview:label];
    return contentView;
}

//先要设Cell可编辑
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    
    if(tableView != _friendTableView) {
        return NO;
    }
    else {
        if (indexPath.section == 0) {
            return NO;
        }else {
//            return YES;  打开后可以删除好友
            return NO;
        }
    
    }
    
//       return YES;
}
//- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    NSDictionary *loginInfo = [[[EaseMob sharedInstance] chatManager] loginInfo];
//    NSString *loginUsername = [loginInfo objectForKey:kSDKUsername];
//    
//    FriendModel *friendModel = _dataSource[indexPath.row];
//    
//    if (_isOwner) {
//        if(tableView != _friendTableView||[friendModel.hx_username isEqualToString:loginUsername]) {
//            return NO;
//        }
//        return YES;
//        
//    }else {
//        return NO;
//        
//    }
//}

//定义编辑样式

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

//进入编辑模式，按下出现的编辑按钮后
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"删除了第%ld行",(long)indexPath.row);
    
    FriendModel *friendModel = _dataSource[indexPath.row];
    
    NSMutableArray *occupants = [NSMutableArray array];
    [occupants addObject:friendModel.hx_username];
    
    [self deleteMemberFromGroup:friendModel];
    
    
    
    [tableView setEditing:NO animated:YES];
}

//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

//设置进入编辑状态时，Cell不会缩进
- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView != _friendTableView) {
        for (FriendModel *friendModel in _dataSource) {
            if ([_resultArray[indexPath.row] isEqualToString:friendModel.name]) {
                ChatController *chatVC = [[ChatController alloc] initWithChatter:friendModel.hx_username isGroup:NO];
                chatVC.customer_id = friendModel.user_id;
                chatVC.hx_username = friendModel.hx_username;
                chatVC.friendType = friendModel.type;
                chatVC.groupID = @"";
                chatVC.title = friendModel.name;
                [self.navigationController pushViewController:chatVC animated:YES];
            }
        }
    }
    else {
        if (indexPath.section == 0) {
            if (indexPath.row == 0) {
                [self.navigationController pushViewController:[ApplyViewController shareController] animated:NO];
            }
            else if (indexPath.row == 1){
                if (_groupController == nil) {
                    _groupController = [[HealthGroupViewController alloc] init];
                }
                else{
                    [_groupController reloadDataSource];
                }
                [self.navigationController pushViewController:_groupController animated:NO];
            }
        }
        else{
            
            FriendModel *friendModel = [_dataSource objectAtIndex:indexPath.row];
            
            if (friendModel) {
                ChatController *chatVC = [[ChatController alloc] initWithChatter:friendModel.hx_username isGroup:NO];
                chatVC.friendType = friendModel.type;
                chatVC.customer_id = friendModel.user_id;
                chatVC.hx_username = friendModel.hx_username;
                chatVC.title = _friendNameArray[indexPath.row];
                chatVC.groupID = @"";
                [self.navigationController pushViewController:chatVC animated:YES];
            }
            
        }

    
    }
}


#pragma mark -------------删除环信还有接口-----备用--------

- (void)deleteMemberFromGroup:(FriendModel *)friendModel {
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    User *user = [User sharedUser];
    
    NSDictionary *parameters = @{@"username":user.hx_username,
                                 @"friendname":friendModel.hx_username};
    NSLog(@"%@",parameters);
    [manager GetWithParameters:parameters method:@"set.hxuser.friend.del" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;
        
        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"删除结果的dictonary :%@",[dictionary description]);
        
        if ([[dictionary objectForKey:@"total"]intValue] == 0)
        {
            [_dataSource removeObject:friendModel];
            [_friendNameArray removeObject:friendModel.name];
            
            [_friendTableView reloadData];
            
            NSString *error = [dictionary objectForKey:@"error"];
//            [SVProgressHUD showErrorWithStatus:error];
            [SVProgressHUD showSuccessWithStatus:error];
            
        }
        else
        {
            NSString *error = [dictionary objectForKey:@"error"];
            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD showErrorWithStatus:error];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
    }];
    
    
}


#pragma mark - UISearchBarDelegate


#pragma mark - UIActionSheetDelegate




@end
